package monkey;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * 三猴吃两桃
 */
public class Test4 {

    private final static Object locker = new Object();
    private static int total = 700;
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        int[] res = new int[3];

        List<Thread> threadList = new ArrayList<>();

        for (int i = 0; i < 3; i++) {
            int index = i;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    System.out.println(index);
                    while (total > 0) {
                        synchronized (locker) {
                            if (total > 0) {
                                res[index] ++;
                                total --;
                            }
                        }
                    }
                }
            };
            Thread thread = new Thread(runnable);
            thread.start();
            threadList.add(thread);
        }
        for (int i = 0; i < threadList.size(); i++) {
            threadList.get(i).join();
        }
        for (int i = 0; i < 3; i++) {
            System.out.println("第 "+(i+1) +" 只猴子吃了 "+res[i] +" 个桃子。");
        }
    }
}
